from flask import Flask, redirect, render_template, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/how2java'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app, use_native_unicode='utf8')

class Category(db.Model):
    __tablename__ = 'category_' #（设置表名）
    id = db.Column(db.Integer, primary_key=True) #（设置主键）
    name = db.Column(db.String(255), unique=True)
    qty = db.Column(db.Integer, unique=True)

# 查 （用到and的时候需要导入库from sqlalchemy import and_）
def query_object():
    result = Category.query.filter()
    print("查询 % r 完成" % Category.__repr__)
    return result

@app.route("/")
def index():
    return redirect("/login")


#html
@app.route("/login")
def login():
    title = "这是我的第一个应用"
    return render_template("login.html", title=title)

#json
@app.route("/json")
def json():
    list = ['figol', 'james']
    return jsonify(list)

#jinja2模板引擎
@app.route("/echarts")
def echarts():
    catetogries = formatQueryData(query_object())
    catetogries = str(catetogries) #将list转换成str
    return render_template("echarts.html", catetogries=catetogries)

def formatQueryData(catetogries):
    res = []
    for c in catetogries:
        res.append({'name':c.name,'qty':c.qty})
    return res

app.run(debug=True)